package cn.com.demo.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import cn.com.demo.shiro.entity.TShiroResPermission;
import cn.com.demo.shiro.service.UserService;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * shiro 配置类，配置FactoryBean及web安全管理器
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager, @Autowired UserService userService){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // shiro 内置过滤器 org.apache.shiro.web.filter.mgt.DefaultFilter
        Map<String, String> map = new LinkedHashMap<>();
        // 登录相关免认证接口
        map.put("/auth/**","anon");
        map.put("/index","anon");
        // 需要demo:p1 权限
//        map.put("/demo/p1","perms[demo:p1]");
        // 需要demo:p2 权限
//        map.put("/demo/p2","perms[demo:p2]");
        // 从数据库中读取权限信息
        List<TShiroResPermission> tShiroResPermissionList = userService.getResPermission();
        for (TShiroResPermission tShiroResPermission : tShiroResPermissionList) {
            map.put(tShiroResPermission.getResPath(),"perms["+tShiroResPermission.getPermissionCode()+"]");
        }
        // 需要登录的接口
        map.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 设置登录页地址，前后端分离项目注意返回需要登录状态码等信息
        shiroFilterFactoryBean.setLoginUrl("/auth/login");
        // 设置未授权地址
        shiroFilterFactoryBean.setUnauthorizedUrl("/auth/forbidden");
        return shiroFilterFactoryBean;
    }

    /**
     * 安全管理器
     * @param userRealm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }
    /**
     * 整合thymeleaf
     */
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
